<template>
  <BasicModal centered destroyOnClose width="400px"
              v-bind="$attrs"
              :title="getTitle"
              :canFullscreen="false"
              :maskClosable="false"
              @ok="handleSubmit"
              @register="registerModal"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, defineProps, ref, unref } from "vue";
  import { BasicModal, useModalInner } from "/@/components/Modal";
  import { BasicForm, useForm } from '/@/components/Form';
  import { FormSchema } from '/@/components/Table';
  import { departSave } from "../customer.api";

  const emit = defineEmits(["success", "register"]);
  const props = defineProps({ customerId: String });
  const isUpdate = ref(true);

  const departFormSchema: FormSchema[] = [
    {
      label: '',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      label: '',
      field: 'customerId',
      component: 'Input',
      show: false,
    },
    {
      label: '类型',
      field: 'parentId',
      required: true,
      component: 'JDictSelectTag',
      componentProps: {
        dictCode: 'customerDepart',
        placeholder: '请选择',
        getPopupContainer: () => document.body,
      },
    },
    {
      label: '名称',
      field: 'areaName',
      required: true,
      component: 'Input',
    },
    {
      label: '地址',
      field: 'dwdz',
      component: 'Input',
    },
  ];

  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: departFormSchema,
    showActionButtonGroup: false,
    mergeDynamicData: props,
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  });

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      if (data.record.tenantId == "0") {
        data.record.tenantId = '';
      }

      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
  });

  //设置标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  //表单提交事件
  async function handleSubmit() {
    try {
      const values = await validate();
      values.customerId = props.customerId;
      setModalProps({ confirmLoading: true });
      if (values.tenantId == '') values.tenantId = "0"
      //提交表单
      await departSave(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

</script>

<style scoped lang="less">

.jeecg-basic-tree {
  border: 1px green solid;
  overflow: auto;

  ::v-deep(.ant-tree) {
    li {
      padding: 0 !important;
    }
  }
}

</style>
